/*
 * ImageAnnotationView.java
 */

package imageannotation;

import Image.ScaledIcon;
import IO.SaveImage;
import IO.ImageFilter;
import IO.TrainingFileFilter;
import Image.SegmentedImage;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Image;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.SwingConstants;

/**
 * The application's main frame.
 */
public class ImageAnnotationView extends FrameView {

    public ImageAnnotationView(SingleFrameApplication app) {
        super(app);

        initComponents();

        // status bar initialization - message timeout, idle icon and busy animation, etc
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
        messageTimer = new Timer(messageTimeout, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                statusMessageLabel.setText("");
            }
        });
        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++) {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
            }
        });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
        statusAnimationLabel.setIcon(idleIcon);
        progressBar.setVisible(false);

        // connecting action tasks to status bar via TaskMonitor
        TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
        taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                String propertyName = evt.getPropertyName();
                if ("started".equals(propertyName)) {
                    if (!busyIconTimer.isRunning()) {
                        statusAnimationLabel.setIcon(busyIcons[0]);
                        busyIconIndex = 0;
                        busyIconTimer.start();
                    }
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(true);
                } else if ("done".equals(propertyName)) {
                    busyIconTimer.stop();
                    statusAnimationLabel.setIcon(idleIcon);
                    progressBar.setVisible(false);
                    progressBar.setValue(0);
                } else if ("message".equals(propertyName)) {
                    String text = (String)(evt.getNewValue());
                    statusMessageLabel.setText((text == null) ? "" : text);
                    messageTimer.restart();
                } else if ("progress".equals(propertyName)) {
                    int value = (Integer)(evt.getNewValue());
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(false);
                    progressBar.setValue(value);
                }
            }
        });
    }

    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = ImageAnnotationApp.getApplication().getMainFrame();
            aboutBox = new ImageAnnotationAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        ImageAnnotationApp.getApplication().show(aboutBox);
    }

	/**
	 * Called by the {@link ImageAnnotationApp} when it receives notification that an
	 * image has been annotated.
	 *
	 * @param image the image which was annotated
	 */
	public void setAnnotatedImage(SegmentedImage image) {
		ScaledIcon si = new ScaledIcon(
			image.getSegmentImageWithWords(), "Annotated Image"
		);
		si.setContainer(Annotated);
		si.setScaleToContainer(true);
		Annotated.setHorizontalAlignment(SwingConstants.CENTER);
		Annotated.setVerticalAlignment(SwingConstants.CENTER);
		Annotated.setIcon(si);
	}

	/**
	 * Display a message in the status bar
	 *
	 * @param message the message to display
	 */
	public void showMessage(String message) {
		statusMessageLabel.setText(message);
	}

	/**
	 * Enable/Disable the load training menu item
	 * @param value true to enable the menu item, false otherwise
	 */
	public void loadTrainingSetEnabled(boolean value) {
		loadTrainingDataMenuItem.setEnabled(value);
	}

	/**
	 * Enable/Disable the open image menu item
	 * @param value true to enable the menu item, false otherwise
	 */
	public void openImageSetEnabled(boolean value) {
		openImageMenuItem.setEnabled(value);
	}

	public boolean useCVScores() {
		return useCVScoresMenuItem.isSelected();
	}

	public boolean useThresholds() {
		return useThresholdMenuItem.isSelected();
	}

	private void loadImageFile(File imageFile) {
		annotateFile = imageFile;
		imageToAnnotatePath = imageFile.getPath();
		String fileName = jFileChooser1.getName(imageFile);
		statusMessageLabel.setText("Open image " + fileName);

		imageIcon = new ScaledIcon(imageToAnnotatePath, "Original Image");
		((ScaledIcon) imageIcon).setContainer(Original);
		((ScaledIcon) imageIcon).setScaleToContainer(true);
		Original.setHorizontalAlignment(SwingConstants.CENTER);
		Original.setVerticalAlignment(SwingConstants.CENTER);
		Original.setIcon(imageIcon);
		Annotated.setIcon(null);

		ImageAnnotationApp.getApplication().annotateImage(imageFile);

		System.out.println("File opened");
	}

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        Original = new javax.swing.JLabel();
        Annotated = new javax.swing.JLabel();
        menuBar = new javax.swing.JMenuBar();
        File = new javax.swing.JMenu();
        loadTrainingDataMenuItem = new javax.swing.JMenuItem();
        openImageMenuItem = new javax.swing.JMenuItem();
        SaveAs = new javax.swing.JMenuItem();
        jSeparator2 = new javax.swing.JSeparator();
        Exit = new javax.swing.JMenuItem();
        jMenu1 = new javax.swing.JMenu();
        useCVScoresMenuItem = new javax.swing.JCheckBoxMenuItem();
        useThresholdMenuItem = new javax.swing.JCheckBoxMenuItem();
        Help = new javax.swing.JMenu();
        AboutAutomaticImageLabelling = new javax.swing.JMenuItem();
        statusPanel = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
        statusMessageLabel = new javax.swing.JLabel();
        statusAnimationLabel = new javax.swing.JLabel();
        progressBar = new javax.swing.JProgressBar();
        jFileChooser1 = new javax.swing.JFileChooser();

        mainPanel.setName("mainPanel"); // NOI18N

        jPanel1.setName("jPanel1"); // NOI18N
        jPanel1.setLayout(new java.awt.GridLayout(1, 0));

        Original.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        Original.setDoubleBuffered(true);
        Original.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        Original.setName("Original"); // NOI18N
        jPanel1.add(Original);

        Annotated.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        Annotated.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        Annotated.setName("Annotated"); // NOI18N
        jPanel1.add(Annotated);

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 646, Short.MAX_VALUE)
                .addContainerGap())
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 201, Short.MAX_VALUE)
                .addContainerGap())
        );

        menuBar.setName("menuBar"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(imageannotation.ImageAnnotationApp.class).getContext().getResourceMap(ImageAnnotationView.class);
        File.setText(resourceMap.getString("File.text")); // NOI18N
        File.setName("File"); // NOI18N

        loadTrainingDataMenuItem.setText(resourceMap.getString("loadTrainingDataMenuItem.text")); // NOI18N
        loadTrainingDataMenuItem.setName("loadTrainingDataMenuItem"); // NOI18N
        loadTrainingDataMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                loadTrainingDataMenuItemActionPerformed(evt);
            }
        });
        File.add(loadTrainingDataMenuItem);

        openImageMenuItem.setText(resourceMap.getString("openImageMenuItem.text")); // NOI18N
        openImageMenuItem.setEnabled(false);
        openImageMenuItem.setName("openImageMenuItem"); // NOI18N
        openImageMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                openImageMenuItemActionPerformed(evt);
            }
        });
        File.add(openImageMenuItem);

        SaveAs.setText(resourceMap.getString("SaveAs.text")); // NOI18N
        SaveAs.setName("SaveAs"); // NOI18N
        SaveAs.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SaveAsActionPerformed(evt);
            }
        });
        File.add(SaveAs);

        jSeparator2.setName("jSeparator2"); // NOI18N
        File.add(jSeparator2);

        Exit.setText(resourceMap.getString("Exit.text")); // NOI18N
        Exit.setName("Exit"); // NOI18N
        Exit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ExitActionPerformed(evt);
            }
        });
        File.add(Exit);

        menuBar.add(File);

        jMenu1.setText(resourceMap.getString("jMenu1.text")); // NOI18N
        jMenu1.setName("jMenu1"); // NOI18N

        useCVScoresMenuItem.setSelected(true);
        useCVScoresMenuItem.setText(resourceMap.getString("useCVScoresMenuItem.text")); // NOI18N
        useCVScoresMenuItem.setName("useCVScoresMenuItem"); // NOI18N
        useCVScoresMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                useCVScoresMenuItemActionPerformed(evt);
            }
        });
        jMenu1.add(useCVScoresMenuItem);

        useThresholdMenuItem.setSelected(true);
        useThresholdMenuItem.setText(resourceMap.getString("useThresholdMenuItem.text")); // NOI18N
        useThresholdMenuItem.setName("useThresholdMenuItem"); // NOI18N
        useThresholdMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                useThresholdMenuItemActionPerformed(evt);
            }
        });
        jMenu1.add(useThresholdMenuItem);

        menuBar.add(jMenu1);

        Help.setText(resourceMap.getString("Help.text")); // NOI18N
        Help.setName("Help"); // NOI18N

        AboutAutomaticImageLabelling.setText(resourceMap.getString("AboutAutomaticImageLabelling.text")); // NOI18N
        AboutAutomaticImageLabelling.setName("AboutAutomaticImageLabelling"); // NOI18N
        Help.add(AboutAutomaticImageLabelling);

        menuBar.add(Help);

        statusPanel.setName("statusPanel"); // NOI18N

        statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N

        statusMessageLabel.setName("statusMessageLabel"); // NOI18N

        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N

        progressBar.setName("progressBar"); // NOI18N

        javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 666, Short.MAX_VALUE)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(statusMessageLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 492, Short.MAX_VALUE)
                .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(statusAnimationLabel)
                .addContainerGap())
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(statusMessageLabel)
                    .addComponent(statusAnimationLabel)
                    .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(3, 3, 3))
        );

        jFileChooser1.setName("jFileChooser1"); // NOI18N

        setComponent(mainPanel);
        setMenuBar(menuBar);
        setStatusBar(statusPanel);
    }// </editor-fold>//GEN-END:initComponents

	private void openImageMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openImageMenuItemActionPerformed
		jFileChooser1.setVisible(true);
		Component L_component = null;
		jFileChooser1.setAcceptAllFileFilterUsed(false);
		jFileChooser1.addChoosableFileFilter(new ImageFilter());

		// Open filechooser so the user can select an image to open
		int returnVal = jFileChooser1.showOpenDialog((Component)L_component);

		// The user has selected a file
		if (returnVal == JFileChooser.APPROVE_OPTION) {
			File file = jFileChooser1.getSelectedFile();

			// Gets file information (Path, name, length, etc.)
			if (!file.isDirectory()) {
				loadImageFile(file);
			}
		}
}//GEN-LAST:event_openImageMenuItemActionPerformed

	private void SaveAsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SaveAsActionPerformed
		ScaledIcon si = (ScaledIcon)Annotated.getIcon();
		if (si != null) {
			// create filename string
	        String ext = imageToAnnotatePath.substring(
				imageToAnnotatePath.indexOf(".")+1
			);
			String folder = imageToAnnotatePath.substring(
				0,imageToAnnotatePath.lastIndexOf("\\")+1
			);
			String filename = imageToAnnotatePath.substring(
				imageToAnnotatePath.lastIndexOf("\\")+1,
				imageToAnnotatePath.lastIndexOf(".")
			);
		    String annotatedPath = folder + filename +
				".annotated." +
				(useCVScores() ? "cv." : "") +
				(useThresholds() ? "t." : "") +
				ext;

			statusMessageLabel.setText("Saving " + annotatedPath);

			Image image = si.getImage();
			BufferedImage  bufferedImage = new BufferedImage(
				image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB
			);
			Graphics big = bufferedImage.getGraphics();
			big.drawImage(image, 0, 0, null);

			// save the annotated image
			SaveImage.save(bufferedImage, annotatedPath);
		}
	}//GEN-LAST:event_SaveAsActionPerformed

	private void ExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ExitActionPerformed
		System.exit(1);
	}//GEN-LAST:event_ExitActionPerformed

	private void loadTrainingDataMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loadTrainingDataMenuItemActionPerformed
		jFileChooser1.setMultiSelectionEnabled(true);
		jFileChooser1.setVisible(true);
		jFileChooser1.setAcceptAllFileFilterUsed(false);
		jFileChooser1.addChoosableFileFilter(new TrainingFileFilter());

		// Open filechooser
		int returnVal = jFileChooser1.showOpenDialog(mainPanel);

		// User selected a file
		if (returnVal == JFileChooser.APPROVE_OPTION) {
			File file = jFileChooser1.getSelectedFile();

			// Call the application to load the data
			if (file.isDirectory()) {
				statusMessageLabel.setText("Loading training data.");
				((ImageAnnotationApp) getApplication()).loadTrainingData(file);
			} else {
				statusMessageLabel.setText("Loading training data.");
				((ImageAnnotationApp) getApplication()).loadTrainingData(
					jFileChooser1.getSelectedFiles()
				);				
			}
		}
}//GEN-LAST:event_loadTrainingDataMenuItemActionPerformed

	private void useCVScoresMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_useCVScoresMenuItemActionPerformed
		if (annotateFile != null) {
			loadImageFile(annotateFile);//GEN-HEADEREND:event_useCVScoresMenuItemActionPerformed
		}
	}//GEN-LAST:event_useCVScoresMenuItemActionPerformed

	private void useThresholdMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_useThresholdMenuItemActionPerformed
		if (annotateFile != null) {
			loadImageFile(annotateFile);
		}
	}//GEN-LAST:event_useThresholdMenuItemActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem AboutAutomaticImageLabelling;
    private javax.swing.JLabel Annotated;
    private javax.swing.JMenuItem Exit;
    private javax.swing.JMenu File;
    private javax.swing.JMenu Help;
    private javax.swing.JLabel Original;
    private javax.swing.JMenuItem SaveAs;
    private javax.swing.JFileChooser jFileChooser1;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JMenuItem loadTrainingDataMenuItem;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JMenuItem openImageMenuItem;
    private javax.swing.JProgressBar progressBar;
    private javax.swing.JLabel statusAnimationLabel;
    private javax.swing.JLabel statusMessageLabel;
    private javax.swing.JPanel statusPanel;
    private javax.swing.JCheckBoxMenuItem useCVScoresMenuItem;
    private javax.swing.JCheckBoxMenuItem useThresholdMenuItem;
    // End of variables declaration//GEN-END:variables

    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;
    private String imageToAnnotatePath = null;
    private File annotateFile = null;
    private ImageIcon imageIcon = null;

    private JDialog aboutBox;
}
